#include <linux/version.h>/* LINUX_VERSION_CODE KERNEL_VERSION()*/
#include <linux/init.h>   /* module_init module_exit */
#include <linux/kernel.h>
#include <linux/module.h> /* MODULE_LICENSE */

#include <linux/platform_device.h>
#include <linux/mod_devicetable.h> /* struct platform_device_id */

#include <linux/of.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/pinconf.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinmux.h>

#include <linux/slab.h>

#include "./timestamp_autogenerated.h"
#include "./version_autogenerated.h"
#include "./sdrv_common.h"

#include "./virtual_pinctrl_driver.h"

// #undef PRT
// #undef PRTE
#ifndef PRT
#define PRT printk
#endif
#ifndef PRTE
#define PRTE printk
#endif

static struct pinctrl_dev *g_pinctrl_dev = NULL;

// ==================== pinctrl_desc.pinctrl_ops ====================
static int virtual_get_groups_count(struct pinctrl_dev *pctldev)
{
    return pctldev->desc->npins;
}

static const char *virtual_get_group_name(struct pinctrl_dev *pctldev,
                                          unsigned selector)
{
    return pctldev->desc->pins[selector].name;
}

static int virtual_get_group_pins(struct pinctrl_dev *pctldev, unsigned selector,
                                  const unsigned **pins,
                                  unsigned *npins)
{
    if (selector >= pctldev->desc->npins)
        return -EINVAL;

    *pins = &pctldev->desc->pins[selector].number;
    *npins = 1;

    return 0;
}

static void virtual_pin_dbg_show(struct pinctrl_dev *pctldev, struct seq_file *s,
                                 unsigned offset)
{
    seq_printf(s, "%s", dev_name(pctldev->dev));
}

/*
 i2cgrp {
         functions = "i2c", "i2c";
         groups = "pin0", "pin1";
         configs = <0x11223344	0x55667788>;
 };

 one pin ==> two pinctrl_map (one for mux, one for config)

 */
static int virtual_dt_node_to_map(struct pinctrl_dev *pctldev,
                                  struct device_node *np,
                                  struct pinctrl_map **map, unsigned *num_maps)
{
    int i;
    int num_pins = 0;
    const char *pin;
    const char *function;
    unsigned int config;
    struct pinctrl_map *new_map;
    unsigned long *configs;

    /* 1. 确定pin个数/分配pinctrl_map */
    while (1)
    {
        if (of_property_read_string_index(np, "groups", num_pins, &pin) == 0)
            num_pins++;
        else
            break;
    }

    new_map = kmalloc(sizeof(struct pinctrl_map) * num_pins * 2, GFP_KERNEL);

    for (i = 0; i < num_pins; i++)
    {
        /* 2. get pin/function/config */
        of_property_read_string_index(np, "groups", i, &pin);
        of_property_read_string_index(np, "functions", i, &function);
        of_property_read_u32_index(np, "configs", i, &config);

        /* 3. 存入pinctrl_map   */
        configs = kmalloc(sizeof(*configs), GFP_KERNEL);

        new_map[i * 2].type = PIN_MAP_TYPE_MUX_GROUP;
        new_map[i * 2].data.mux.function = function;
        new_map[i * 2].data.mux.group = pin;

        new_map[i * 2 + 1].type = PIN_MAP_TYPE_CONFIGS_PIN;
        new_map[i * 2 + 1].data.configs.group_or_pin = pin;
        new_map[i * 2 + 1].data.configs.configs = configs;
        configs[0] = config;
        new_map[i * 2 + 1].data.configs.num_configs = 1;
    }

    *map = new_map;
    *num_maps = num_pins * 2;

    return 0;
}
static void virtual_dt_free_map(struct pinctrl_dev *pctldev,
                                struct pinctrl_map *map, unsigned num_maps)
{
    while (num_maps--)
    {
        if (map->type == PIN_MAP_TYPE_CONFIGS_PIN)
            kfree(map->data.configs.configs);

        kfree(map);
        map++;
    }
}

static const struct pinctrl_ops virtual_pctrl_ops = {
    .get_groups_count = virtual_get_groups_count,
    .get_group_name = virtual_get_group_name,
    .get_group_pins = virtual_get_group_pins,
    .pin_dbg_show = virtual_pin_dbg_show,
    .dt_node_to_map = virtual_dt_node_to_map,
    .dt_free_map = virtual_dt_free_map,
};

// ==================== pinctrl_desc.pinmux_ops ====================
struct virtual_functions_desc {
    const char *func_name;
    const char **groups;
    int num_groups;
};

static const char *func0_grps[] = {"pin0", "pin1", "pin2", "pin3"};
static const char *func1_grps[] = {"pin0", "pin1"};
static const char *func2_grps[] = {"pin2", "pin3"};

static struct virtual_functions_desc g_funcs_desc[] = {
    {"gpio", func0_grps, 4},
    {"i2c", func1_grps, 2},
    {"uart", func2_grps, 2},
};

static int virtual_pmx_get_funcs_count(struct pinctrl_dev *pctldev)
{
    return ARRAY_SIZE(g_funcs_desc);
}

static const char *virtual_pmx_get_func_name(struct pinctrl_dev *pctldev,
                                             unsigned selector)
{
    return g_funcs_desc[selector].func_name;
}

static int virtual_pmx_get_groups(struct pinctrl_dev *pctldev, unsigned selector,
                                  const char *const **groups,
                                  unsigned *const num_groups)
{
    *groups = g_funcs_desc[selector].groups;
    *num_groups = g_funcs_desc[selector].num_groups;

    return 0;
}

static int virtual_pmx_set(struct pinctrl_dev *pctldev, unsigned selector,
                           unsigned group)
{
    printk("set %s as %s\n", pctldev->desc->pins[group].name, g_funcs_desc[selector].func_name);
    return 0;
}

static const struct pinmux_ops virtual_pmx_ops = {
    .get_functions_count = virtual_pmx_get_funcs_count,
    .get_function_name = virtual_pmx_get_func_name,
    .get_function_groups = virtual_pmx_get_groups,
    .set_mux = virtual_pmx_set,
};

// ==================== pinctrl_desc.pinconf_ops ====================
static unsigned long g_configs[4] = {0};
int (*pin_config_get) (struct pinctrl_dev *pctldev,
    unsigned pin,
    unsigned long *config);

static int virtual_pinconf_get(struct pinctrl_dev *pctldev,
                               unsigned pin_id, unsigned long *config)
{
    *config = g_configs[pin_id];
    return 0;
}

static int virtual_pinconf_set(struct pinctrl_dev *pctldev,
                               unsigned pin_id, unsigned long *configs,
                               unsigned num_configs)
{
    if (num_configs != 1)
        return -EINVAL;

    g_configs[pin_id] = *configs;

    printk("config %s as 0x%lx\n", pctldev->desc->pins[pin_id].name, *configs);

    return 0;
}

static void virtual_pinconf_dbg_show(struct pinctrl_dev *pctldev,
                                     struct seq_file *s, unsigned pin_id)
{
    seq_printf(s, "0x%lx", g_configs[pin_id]);
}

static void virtual_pinconf_group_dbg_show(struct pinctrl_dev *pctldev,
                                           struct seq_file *s, unsigned pin_id)
{
    seq_printf(s, "0x%lx", g_configs[pin_id]);
}

static const struct pinconf_ops virtual_pinconf_ops = {
    .pin_config_get = virtual_pinconf_get,
    .pin_config_set = virtual_pinconf_set,
    .pin_config_dbg_show = virtual_pinconf_dbg_show,
    .pin_config_group_dbg_show = virtual_pinconf_group_dbg_show,
};

// ==================== platform driver ====================
static const struct pinctrl_pin_desc g_pins_desc[] = {
    {0, "pin0", NULL},
    {1, "pin1", NULL},
    {2, "pin2", NULL},
    {3, "pin3", NULL},
};

/**
 * @brief  sdrv_driver_probe()
 * @note   平台设备的探测函数
 * @param [in]
 * @param [out]
 * @retval 
 */
static int sdrv_driver_probe(struct platform_device *pdev)
{
    int ret = 0;
    struct pinctrl_desc *pictrl = NULL;
    PRT("probing platform device & driver!pdev->name=%s\n", pdev->name);
    /* a. 分配pinctrl_desc */
	pictrl = devm_kzalloc(&pdev->dev, sizeof(*pictrl), GFP_KERNEL);
	/* b. 设置pinctrl_desc */
	pictrl->name = dev_name(&pdev->dev);
	pictrl->owner = THIS_MODULE;
	/* b.1 pins and group */
	pictrl->pins = g_pins_desc;
	pictrl->npins = ARRAY_SIZE(g_pins_desc);
	pictrl->pctlops = &virtual_pctrl_ops;
	/* b.2 pin mux */
	pictrl->pmxops = &virtual_pmx_ops;
	/* b.3 pin config */
	pictrl->confops = &virtual_pinconf_ops;
	/* c. 注册pinctrl_desc */
	g_pinctrl_dev = devm_pinctrl_register(&pdev->dev, pictrl, NULL);
	
    return ret;
}

/**
 * @brief  sdrv_driver_remove()
 * @note   平台设备的移除函数
 * @param [in]
 * @param [out]
 * @retval 
 */
static int sdrv_driver_remove(struct platform_device *pdev)
{
    PRT("removing platform driver!pdev->name=%s\n", pdev->name);
    return 0;
}

/* 设备树匹配列表 */
static const struct of_device_id virtual_pinctrl_of_match[] = {
	{ .compatible = "alpha,virtual_pinctrl" }, // 这里用于匹配设备树中的 compatible 属性节点
	{ /* Sentinel */ }
};

/**
 * 定义平台驱动结构体
 */
static struct platform_driver g_sdrv_driver_platform = {
    .probe = sdrv_driver_probe,   // 平台设备的探测函数指针
    .remove = sdrv_driver_remove, //  平台设备的移除函数指针
    .driver = {
        .owner = THIS_MODULE,
        .name = "virtual_pinctrl_driver", // 和设备名称相同时，可以匹配成功
                                          // 会在 /sys/bus/platform/drivers中创建对应目录，
                                          // 即/sys/bus/platform/drivers/driver-name
		.of_match_table	= of_match_ptr(virtual_pinctrl_of_match), /* 设备树匹配表 */
    },
};

/**
 * @brief  sdrv_driver_init
 * @note   调用driver_register函数注册我们的驱动
 * @param [in]
 * @param [out]
 * @retval 
 */
static __init int sdrv_driver_init(void)
{
    int ret = 0;
	printk("*** [%s:%d]Build Time: %s %s, git version:%s LINUX_VERSION=%d.%d.%d ***\n", __FUNCTION__,
           __LINE__, KERNEL_KO_DATE, KERNEL_KO_TIME, KERNEL_KO_VERSION, 
           (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, LINUX_VERSION_CODE & 0xff);

	// 注册平台驱动
    ret = platform_driver_register(&g_sdrv_driver_platform);
    if (ret) 
    {
        PRT("Failed to register platform driver!ret=%d\n", ret);
        goto err_platform_driver_register;
    }

    //PRT("sdrv_driver module init success!\n");
	return 0;

err_platform_driver_register:
    return ret;
}

/**
 * @brief  sdrv_driver_exit
 * @note   注销驱动
 * @param [in]
 * @param [out]
 * @retval 
 */
static __exit void sdrv_driver_exit(void)
{
    // 注销平台驱动
    platform_driver_unregister(&g_sdrv_driver_platform);
    //PRT("sdrv_driver module exit!\n");
}

module_init(sdrv_driver_init); // 将__init定义的函数指定为驱动的入口函数
module_exit(sdrv_driver_exit); // 将__exit定义的函数指定为驱动的出口函数

/* 模块信息(通过 modinfo xxx.ko 查看) */
MODULE_LICENSE("GPL v2");            /* 源码的许可证协议 */
MODULE_AUTHOR("sumu");               /* 字符串常量内容为模块作者说明 */
MODULE_DESCRIPTION("Description");   /* 字符串常量内容为模块功能说明 */
MODULE_ALIAS("module's other name"); /* 字符串常量内容为模块别名 */
